package com.jrx.anytxn.reporting.service.impl;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.bean.PaymentDataBean;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.dto.MrPaymentLogRes;
import com.jrx.anytxn.reporting.entity.MrPaymentLog;
import com.jrx.anytxn.reporting.mapper.ext.ExtMrPaymentLogMapper;
import com.jrx.anytxn.reporting.service.IPaymentLogDataService;
import com.jrx.anytxn.transaction.entity.TlPaymentAllocationLog;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.entity.TlPaymentMapping;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentAllocationLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentMappingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class PaymentLogDataServiceImpl implements IPaymentLogDataService {

    Logger logger = LoggerFactory.getLogger(PaymentLogDataServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtTlPaymentAllocationLogMapper extTlPaymentAllocationLogMapper;
    @Resource
    private ExtTlPaymentMappingMapper extTlPaymentMappingMapper;
    @Resource
    private ExtMrPaymentLogMapper extMrPaymentLogMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Override
    public PaymentDataBean assemPaymentLogData(TlPaymentLog tlPaymentLog) throws TxnBizException {
        PaymentDataBean paymentDataBean = new PaymentDataBean();
        List<MrPaymentLog> paymentList = new ArrayList<>();

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);

        // 根据扣款流水查询 还款流水与订单关联表 只要针对客户级别扣款
        List<TlPaymentMapping> mappingList = extTlPaymentMappingMapper.selectByPaymentSeqAndCustomerId(tlPaymentLog.getSeqNo(),tlPaymentLog.getCustomerId(),tlPaymentLog.getTenantId());

        for(TlPaymentMapping mapping : mappingList){
            logger.info( "tlPaymentLog 流水号：{},客户号：{}" ,tlPaymentLog.getSeqNo(),tlPaymentLog.getCustomerId());
            MrPaymentLog mrPaymentLog = BeanMapping.copy(tlPaymentLog,MrPaymentLog.class);
            mrPaymentLog.setBusinessDate(org.getNextProcessingDate());
            mrPaymentLog.setLoanId(mapping.getLoanId());//订单号
            paymentDataBean.setFlag(0);//新增
            try {
                mrPaymentLog.setId(segmentService.getId(ReportingConstant.MR_PAYMENT_LOG_ID));
            } catch (SegmentException e) {
                logger.error("主键生成错误", e);
                throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
            }
            mrPaymentLog.setPostingDate(tlPaymentLog.getBusinessDate());//发生日期
            BigDecimal totalAmount = BigDecimal.ZERO;//总金额
            BigDecimal actualcorp = BigDecimal.ZERO;//本金
            BigDecimal actualinte = BigDecimal.ZERO;//利息
            BigDecimal penalty = BigDecimal.ZERO;//罚息
            BigDecimal repayFee = BigDecimal.ZERO;//费用
            BigDecimal prepayFee = BigDecimal.ZERO;//提前结清费用
            BigDecimal compoundInterest = BigDecimal.ZERO;//复利

            //只有成功的还款才需要获取交易账户
            if(ReportingConstant.DISBURSEMENT_LOG_SUM_STATUS_S.equals(tlPaymentLog.getSumStatus())){
                //获取交易账户
                TlPaymentAllocationLog tlPaymentAllocationLog = new TlPaymentAllocationLog();
                tlPaymentAllocationLog.setCustomerId(tlPaymentLog.getCustomerId());
                tlPaymentAllocationLog.setTenantId(tlPaymentLog.getTenantId());
                tlPaymentAllocationLog.setSeqNo(tlPaymentLog.getSeqNo());
                tlPaymentAllocationLog.setLoanId(mapping.getLoanId());
                tlPaymentAllocationLog.setAccountType(ReportingConstant.PAYMENT_ALLOCATION_TYPE_09);
                List<TlPaymentAllocationLog> allocationLogList = extTlPaymentAllocationLogMapper.selectListByCondition(tlPaymentAllocationLog);

                for(TlPaymentAllocationLog log : allocationLogList){
                    mrPaymentLog.setBillingTenor(log.getBillingTenor());//当前期次
                    mrPaymentLog.setTotalTenor(log.getTotalTenor());//总期次
                    mrPaymentLog.setPartnerId(log.getPartnerId());//合作方ID
                    mrPaymentLog.setFundId(log.getFundId());//资金源id
                    mrPaymentLog.setRevealMobel(log.getRevealMobel());//兜底模式
                    mrPaymentLog.setTotalDays(log.getTotalDays());//贷款期限天数
                    mrPaymentLog.setCompensatoryFlag(log.getCompensatoryFlag());//代偿标识
                    mrPaymentLog.setNonAccrualsFlag(log.getNonAccrualsFlag());//非应记状态
                    switch (log.getConnectAccountType()){
                        case ReportingConstant.ACCOUNT_TYPE_06 :
                            actualcorp = actualcorp.add(log.getPostingAmount());
                            break;
                        case ReportingConstant.ACCOUNT_TYPE_04 :
                            actualinte = actualinte.add(log.getPostingAmount());
                            break;
                        case ReportingConstant.ACCOUNT_TYPE_11 :
                            penalty = penalty.add(log.getPostingAmount());
                            break;
                        case ReportingConstant.ACCOUNT_TYPE_12 :
                            compoundInterest = compoundInterest.add(log.getPostingAmount());
                            break;
                    }
                    //费用计算
                    if(log.getTxnCode().substring(3,4).equals("2")){
                        switch (log.getTxnCode().substring(5,6)){
                            case "1"://一次性手续费
                                repayFee = repayFee.add(log.getPostingAmount());
                                break;
                            case "2"://分期手续费
                                repayFee = repayFee.add(log.getPostingAmount());
                                break;
                            case "3"://提前还款手续费还款
                                repayFee = repayFee.add(log.getPostingAmount());
                                break;
                            case "4"://提前结清手续费还款
                                prepayFee = prepayFee.add(log.getPostingAmount());
                                break;
                        }
                    }
                }
            }
            mrPaymentLog.setInputDate(tlPaymentLog.getCreateTime());//源表数据创建时间
            mrPaymentLog.setActualcorp(actualcorp);
            mrPaymentLog.setActualinte(actualinte);
            mrPaymentLog.setPenalty(penalty);
            mrPaymentLog.setRepayFee(repayFee);
            mrPaymentLog.setPrepayFee(prepayFee);
            mrPaymentLog.setRepayCompoundInterest(compoundInterest);
            totalAmount = actualcorp.add(actualinte).add(penalty).add(repayFee).add(prepayFee).add(compoundInterest);
            mrPaymentLog.setTotalAmount(totalAmount);//扣款金额

            paymentList.add(mrPaymentLog);
        }
        paymentDataBean.setMrPaymentLog(paymentList);

        return paymentDataBean;
    }

    @Override
    public void generatePaymentLogInfo(PaymentDataBean paymentDataBean) {
        extMrPaymentLogMapper.batchInsertMrPaymentLog(paymentDataBean.getMrPaymentLog());
    }

    @Override
    public List<MrPaymentLogRes> getMrPaymentLogByTenantIdAndLoanIdAndCusId(String tenantId, String loanId, String customerId) {
        List<MrPaymentLog> mrPaymentLogs = extMrPaymentLogMapper.selectMrPaymentLogByTenantIdAndLoanIdAndCusId(tenantId, loanId, customerId);
        return BeanMapping.copyList(mrPaymentLogs,MrPaymentLogRes.class);
    }
}
